//
//  ZlExciseBeginSheetViewController.m
//  ZLExamination
//
//  Created by Lei_Zhong_Xun on 2017/9/5.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZlExciseBeginSheetViewController.h"
#import "ZLExamBeginSheetCommitView.h"
#import "ZLExciseBeginSheetTableViewCell.h"
#import "ZLExciseBeginModel.h"
#import "ZLExciseResultViewController.h"

static NSString *const ZLExciseBeginSheetTableViewCellID = @"ZLExciseBeginSheetTableViewCellID";

@interface ZlExciseBeginSheetViewController ()
@property (nonatomic, strong) UIButton *commitPaperBtn; // 交卷
@property (nonatomic, strong) ZLExamBeginSheetCommitView *commitView; //交卷提示
@property (nonatomic, strong) UILabel *timeLbl; //计时

@property (nonatomic) BOOL singleAllAnswer; //单选全部回答
@property (nonatomic) BOOL multipleAllAnswer; //多选全部回答

/** 所有题的考试答案数组*/
@property (nonatomic,strong) NSMutableArray* allAnswerArray;


@end

@implementation ZlExciseBeginSheetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self showBackButtonWithTitle:@"╳" withFont:[UIFont boldSystemFontOfSize:20]];
    
    self.navigationItem.title = @"答题卡";
    [self.myTableView registerClass:[ZLExciseBeginSheetTableViewCell class] forCellReuseIdentifier:ZLExciseBeginSheetTableViewCellID];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.commitPaperBtn];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.commitView];
    
    [self clickActionCallBack];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.myTableView reloadData];
}

#pragma mark - 点击事件
- (void)commitPaperClick:(UIButton *)sender {
#pragma mark 是否交卷弹窗提示
    
    _singleAllAnswer = YES;
    _multipleAllAnswer = YES;
    //遍历单选model数组, 其中有一个没答上, 就给NO
    [_questions[0] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZLExciseBeginModel *model = (ZLExciseBeginModel *)obj;
        if(model.isAnswer == NO) {
            _singleAllAnswer = NO;
            *stop = YES;
        }
    }];
    //遍历多选model数组, 其中有一个没答上, 就给NO
    [_questions[1] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZLExciseBeginModel *model = (ZLExciseBeginModel *)obj;
        if (model.isAnswer == NO) {
            _multipleAllAnswer = NO;
            *stop = YES;
        }
    }];
    //当单选题并且多选全部选择完成后, 显示是否要提交卷子
    if (_singleAllAnswer&&_multipleAllAnswer) {
        [_commitView showCommitViewAllAnswer];
    } else {
        //提交没有答完
        kCX_LOG(@"你有题目没有答完");
        [_commitView showCommitViewUnAnswer];
        //        [_commitView showCommitViewAutoCommit];
    }
}

#pragma mark - 点击答题卡中额对应提 传递给控制前, 跳转到对应的练习题
- (void)scroolToDesignationRowWith:(NSInteger)rowNumber {
    if (_clickCallBack) {
        _clickCallBack(rowNumber);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 确定交卷
- (void)clickActionCallBack {
    _allAnswerArray = [NSMutableArray array];
    __weak typeof(self) weakSelf = self;
    [_commitView setEnterCallBack:^{
        kCX_LOG(@"交卷");
        NSMutableArray<ZLExciseBeginModel *> *singleArr = weakSelf.questions[0];
        NSMutableArray<ZLExciseBeginModel *> *multipleArr = weakSelf.questions[1];
        //打印单选选择的内容
        [singleArr enumerateObjectsUsingBlock:^(ZLExciseBeginModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.questionAnswer.length) {
                NSString *answerStr = [NSString stringWithFormat:@"%ld:%@", idx + 1, obj.questionAnswer];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
                
            } else {
                NSString *answerStr = [NSString stringWithFormat:@"%ld: ", idx + 1];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
            }
        }];
        
        //打印多选选择的内容
        [multipleArr enumerateObjectsUsingBlock:^(ZLExciseBeginModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.answers.count != 0) {
                //obj.answers数组里面按照abcd 排序 后放到resultArray数组里
                NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
                NSWidthInsensitiveSearch|NSForcedOrderingSearch;
                
                NSComparator sort = ^(NSString *obj1,NSString *obj2){
                    
                    NSRange range = NSMakeRange(0,obj1.length);
                    
                    return [obj1 compare:obj2 options:comparisonOptions range:range];
                };
                NSArray *resultArray = [obj.answers sortedArrayUsingComparator:sort];
                //                obj.answers
                NSString *tempStr = [resultArray componentsJoinedByString:@";"];
                NSString *answerStr = [NSString stringWithFormat:@"%@:%@", obj.n_id, tempStr];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
                
            } else {
                NSString *answerStr = [NSString stringWithFormat:@"%@: ", obj.n_id];
                NSLog(@"%@", answerStr);
                [weakSelf.allAnswerArray addObject:answerStr];
            }
        }];
        NSString *scoreStr = [weakSelf.allAnswerArray componentsJoinedByString:@"|"];
        NSLog(@"%@", scoreStr);
        //提交练习答案信息
        [weakSelf submitExamLoadDataWith:scoreStr];
    }];
}

- (void)submitExamLoadDataWith:(NSString *)scoreStr
{
//    NSDictionary *param = @{@"curriculum_id":_curriculum_id,
//                            @"chapter_id":_chapter_id,
//                            @"questions_id":_questions_id,
//                            @"score" : scoreStr};

    NSDictionary *param = @{@"curriculum_id":_curriculum_id,
                            @"chapter_id":_chapter_id,
                            @"score" : scoreStr};

    NSLog(@"%@", param);
    YCRequestDataService *manager = [YCRequestDataService sharedManager];
    [manager Post:@"curriculum/exercises/sub_exercises" parameters:param success:^(id response) {
        NSLog(@"%@", response);
        if (response[@"error_code"]) {
            NSLog(@"%@",response[@"error_msg"]);
            [manager showHUDSleepText:self withTitle:response[@"error_msg"]];

        } else {
            ZLExciseResultViewController *erVC = [[ZLExciseResultViewController alloc] init];
            erVC.curriculum_id = _curriculum_id;
            erVC.chapter_id = _chapter_id;
            erVC.oneMoreExcisemodel = _model;
            [self.navigationController pushViewController:erVC animated:YES];
        }
    } failure:^{
        NSLog(@"网络或服务器出错");
    }];
}

#pragma mark - 接受全部练习题
- (void)setQuestions:(NSArray<NSMutableArray *> *)questions
{
    _questions = questions;
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    
    ZLExciseBeginSheetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ZLExciseBeginSheetTableViewCellID  forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        [cell setNumbersWithRows:[_questions[0] count] withSingles:_questions[indexPath.section]];
        
    } else {
        [cell setNumbersWithRows:[_questions[1] count] withMultiple:_questions[indexPath.section] withSingleRows:[_questions[0] count]];
    }

    //回调给VC 当前的题号
    cell.clickCallBack = ^(NSInteger number) {
        [weakSelf scroolToDesignationRowWith:number];
    };
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger rows = 0;
    
    if (indexPath.section == 0) {
        CGFloat a = [_questions[0] count]/5.;
        NSInteger b = [_questions[0] count]/5;
        rows = a>b? b+1: b;
    } else {
        CGFloat a = [_questions[1] count]/5.;
        NSInteger b = [_questions[1] count]/5;
        rows = a>b? b+1: b;
    }
    
    return rows*(kSCREEN_WIDTH/5);
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"单选题";
    } else {
        return @"多选题";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

#pragma mark - 布局
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [_commitPaperBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    [self.myTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(_commitPaperBtn.mas_top);
    }];
}

#pragma mark - lazy load
- (ZLExamBeginSheetCommitView *)commitView {
    if (!_commitView) {
        _commitView = [[ZLExamBeginSheetCommitView alloc] initWithFrame:(CGRect){0, 0, kSCREEN_WIDTH, kSCREENH_HEIGHT}];
    }
    return _commitView;
}

- (UIButton *)commitPaperBtn {
    if (!_commitPaperBtn) {
        _commitPaperBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitPaperBtn.backgroundColor = kMY_BLUE_COLOR;
        [_commitPaperBtn setTitle:@"交卷" forState:UIControlStateNormal];
        [_commitPaperBtn addTarget:self action:@selector(commitPaperClick:) forControlEvents:UIControlEventTouchUpInside];
        _commitPaperBtn.titleLabel.font = kMyFont(15);
    }
    return _commitPaperBtn;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
